from machine import ADC, Pin, unique_id, Timer
import ubinascii

# 设备ID
CLIENT_ID = ubinascii.hexlify(unique_id()).decode("utf-8")
# MQTT 主题路径
TOPIC = "device/soilmoisture/{}".format(CLIENT_ID)
TOPIC = TOPIC.encode()
temp_client = None
# 初始化ADC
adc = ADC(Pin(34))  # 假设将传感器连接至GPIO34
adc.atten(ADC.ATTN_11DB)  # 配置最大量程为3.3V


def soilmoisture_callback(t):
    raw_value = adc.read()  # 从ADC读取原始数值
    # 确保是数字类型后进行除法运算并保留2位小数
    if isinstance(raw_value, int):
        normalized_value = round((raw_value / 4095) * 100, 2)
    else:
        try:
            # 尝试将值转换为整数
            int_value = int(raw_value)
            normalized_value = round((int_value / 4095) * 100, 2)
        except ValueError:
            # 无法转换为整数，打印错误信息
            print("读取的值不是整数:", raw_value)
            return  # 退出函数

    # 继续你的函数其余部分...
    print("土壤湿度（0为最湿润，1为最干燥）:", normalized_value)
    temp_client.publish(TOPIC, str(normalized_value))
    return normalized_value


def register_soilmoisture_topic(client):
    global temp_client
    temp_client = client
    # temp_client.subscribe(TOPIC)
    # temp_timer = Timer(2)
    # temp_timer.init(period=60000, mode=Timer.PERIODIC, callback=soilmoisture_callback)
